<template>
  <div>
    <el-card shadow="never" :style="{height: documentHeight + 'px', overflow:'auto' }">
      <!--     <div style="float: left">-->
      <el-form :inline="true">
        <el-form-item label="任务名称" label-width="65px" prop="datasourceName">
          <el-input placeholder="请输入名称" size="mini" v-model="queryform.jobName"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="上级任务" label-width="65px" prop="datasourceName">
          <el-select filterable style="width: 90%" size="mini" v-model="queryform.parentJobId"
                     placeholder="请选择上级任务" clearable>
            <el-option
              v-for="item in parentJobIdoptions"
              :key="item.id"
              :label="item.jobName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="任务类型" label-width="60px" prop="datasourceName">
          <el-select filterable style="width: 90%" size="mini" v-model="queryform.objType"
                     placeholder="请选择任务类型" clearable>
            <el-option label="数据开发" value="1"></el-option>
            <el-option label="数据集成" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="主题" label-width="40px" prop="datasourceName">
          <el-select filterable style="width: 90%" size="mini" v-model="queryform.flowRootId"
                     placeholder="请选择主题" clearable>
            <el-option
              v-for="item in flowRootIdoptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button size="mini" type="primary" @click="queryDataSource()">查询</el-button>
          <el-button size="mini" type="primary" @click="addDataSourcedialog()">新增</el-button>
        </el-form-item>
      </el-form>
      <!--       </div>-->
      <div style="width: 100%;margin-top: -40px">
        <table-change @change="tableSize = $event" style="float: right;" />
        <el-table
          :height="documentHeight-181"
          :size="tableSize"
          :cell-style="({ column })=>column.type==='index'&&'color:#999999'"
          :data="tableData"
          row-key="id"
          style="width: 100%;">
          <el-table-column
            prop="id"
            align="center"
            label="id"
            min-width="50">
          </el-table-column>
          <el-table-column
            align="center"
            prop="jobName"
            label="任务名称"
            show-overflow-tooltip
            min-width="150">
          </el-table-column>
          <el-table-column
            align="center"
            prop="objType"
            label="任务类型"
            min-width="90">
            <template v-slot="{row}">
              <span v-if="row.objType==='1'">数据开发</span>
              <span v-if="row.objType==='2'">数据集成</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="jobCron"
            label="cron"
            min-width="90">
          </el-table-column>
          <el-table-column
            align="center"
            prop="flowRootName"
            label="主题"
            show-overflow-tooltip
            min-width="100">
          </el-table-column>
          <el-table-column
            align="center"
            prop="parentJobName"
            show-overflow-tooltip
            label="上级任务"
            min-width="100">
          </el-table-column>
          <el-table-column
            align="center"
            prop="threads"
            label="并发数"
            min-width="60">
            <template v-slot="{row}">
              <span v-if="row.threads">{{ row.threads }}</span>
              <span v-else>不限制</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="executorTimeout"
            label="超时时间(秒)"
            min-width="90">
          </el-table-column>
          <el-table-column
            align="center"
            prop="server"
            label="执行节点"
            min-width="110">
          </el-table-column>
          <el-table-column
            prop="triggerTime"
            align="center"
            label="触发时间"
            min-width="150">
          </el-table-column>
          <el-table-column
            prop="startTime"
            label="开始时间"
            header-align="center"
            align="center"
            min-width="150">
          </el-table-column>
          <el-table-column
            prop="overTime"
            label="结束时间"
            align="center"
            min-width="150">
          </el-table-column>
          <el-table-column
            prop="result"
            label="执行结果"
            align="center"
            min-width="80">
            <template v-slot="{row}">
              <span v-if="row.result==='1'">已经启动</span>
              <span v-if="row.result==='2'">执行成功</span>
              <span v-if="row.result==='3'" style="color: #FC5A5A">启动异常</span>
              <span v-if="row.result==='4'" style="color: #FC5A5A">执行异常 </span>
              <span v-if="row.result==='5'">停止 </span>
            </template>
          </el-table-column>
          <el-table-column
            prop="result"
            label="下次触发时间"
            align="center"
            min-width="100">
            <template v-slot="{row}">
              <el-popover
                placement="bottom"
                trigger="click"
              >
                <span v-html="nextDate"></span>
                <el-link slot="reference" :click-change-color="true" :underline="false" style="margin-left: 5px"
                         @click="queryDate(row)" type="primary">查看
                </el-link>
              </el-popover>

            </template>
          </el-table-column>
          <el-table-column
            header-align="center"
            align="center"
            label="状态"
            min-width="50">
            <template v-slot="{row}">
              <el-switch
                size="mini"
                @change="dOJob(row)"
                :active-color="$themes.getSwitch().on"
                :inactive-color="$themes.getSwitch().down"
                v-model="row.status"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column
            prop="address"
            header-align="center"
            align="center"
            label="操作"
            fixed="right"
            min-width="150">
            <template slot-scope="scope">
              <el-link :click-change-color="true" :underline="false" style="margin-left: 5px"
                       @click="runDataSource(scope.row)" type="primary">执行
              </el-link>
              <span style="margin-left: 5px;color:#CCCCCC">|</span>
              <el-link :click-change-color="true" :underline="false" style="margin-left: 5px"
                       @click="querylog(scope.row)" type="primary">查看日志
              </el-link>
              <span style="margin-left: 5px;color:#CCCCCC">|</span>
              <el-link :click-change-color="true" :underline="false" style="margin-left: 5px"
                       @click="stopDataSource(scope.row)" type="primary">停止
              </el-link>
              <span style="margin-left: 5px;color:#CCCCCC">|</span>
              <el-link :click-change-color="true" :underline="false" style="margin-left: 5px"
                       @click="editDataSource(scope.row)" type="primary">编辑
              </el-link>
              <span style="margin-left: 5px;color:#CCCCCC">|</span>
              <el-link :underline="false" style="margin-left: 5px" @click="deleteDataSource(scope.row)" type="primary">
                删除
              </el-link>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          style="margin-top: 5px;float: right"
          small
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-size=pagesize
          :page-sizes="[10, 20, 30, 50]"
          layout="total,prev, sizes,pager, next,jumper"
          :total=total>
        </el-pagination>
      </div>

    </el-card>
    <el-dialog @close="addDataSource(false)" width="40%" :title="dialogtitle" top="10px" style="z-index:1000000"
               :close-on-click-modal=false :visible.sync="dialogFormVisible">
      <el-form ref="addsourceformref" :model="addsourceform" :rules="fromrules">
        <el-form-item label="任务名称" label-width="120px">
          <el-input style="width: 90%" placeholder="" size="mini" v-model="addsourceform.jobName"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="任务类型" label-width="120px">
          <el-radio v-model="addsourceform.objType" label="1" @change="handleRadioChange">数据开发</el-radio>
          <el-radio v-model="addsourceform.objType" label="2" @change="handleRadioChange">数据集成</el-radio>
        </el-form-item>
        <el-form-item label="业务流程" v-if="addsourceform.objType==='1'" label-width="120px" prop="objId">
          <el-select filterable style="width: 90%" size="mini" v-model="addsourceform.objId"
                     placeholder="请选择业务流程">
            <el-option
              v-for="item in addsourceoptions"
              :key="item.key"
              :label="item.value"
              :value="item.key">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据集成" v-if="addsourceform.objType==='2'" label-width="120px" prop="objId">
          <el-select filterable style="width: 90%" size="mini" v-model="addsourceform.objId"
                     placeholder="请选择数据集成">
            <el-option
              v-for="item in collectdataoptions"
              :key="item.key"
              :label="item.value"
              :value="item.key">
            </el-option>
          </el-select>
        </el-form-item>
        <!--        <el-form-item label="超时时间" label-width="120px">-->
        <!--          <el-input style="width: 90%" placeholder="" size="mini" v-model="addsourceform.executorTimeout"-->
        <!--                    autocomplete="off"></el-input>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="重试次数" label-width="120px">-->
        <!--          <el-input style="width: 90%" placeholder="" size="mini" v-model="addsourceform.executorFailRetryCount"-->
        <!--                    autocomplete="off"></el-input>-->
        <!--        </el-form-item>-->


        <!--          <el-input style="width: 90%" placeholder="" size="mini" v-model="addsourceform.subJobId"-->
        <!--                    autocomplete="off"></el-input>-->

        <el-form-item label="描述" label-width="120px">
          <el-input style="width: 90%" type="textarea" :rows="4" placeholder="" size="mini"
                    v-model="addsourceform.jobDesc"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="触发类型" label-width="120px">
          <el-radio v-model="addsourceform.triggerType" label="1">定时</el-radio>
          <el-radio v-model="addsourceform.triggerType" label="2">依赖</el-radio>
        </el-form-item>
        <el-form-item label="最大并发数" label-width="120px">
          <el-input style="width: 90%" placeholder="空表示不限制" size="mini"
                    v-model="addsourceform.threads"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="超时时间(秒)" label-width="120px">
          <el-input style="width: 90%" size="mini"
                    v-model="addsourceform.executorTimeout"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="重试次数" label-width="120px">
          <el-input style="width: 90%" size="mini"
                    v-model="addsourceform.executorFailRetryCount"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="遇错继续触发" label-width="120px">
          <el-radio v-model="addsourceform.errorContinue" label="1">是</el-radio>
          <el-radio v-model="addsourceform.errorContinue" label="0">否</el-radio>
        </el-form-item>
        <el-form-item v-if="addsourceform.triggerType==='1'" label="cron表达式" label-width="120px" prop="jobCron">
          <el-input style="width: 90%" placeholder="" size="mini" v-model="addsourceform.jobCron"
                    autocomplete="off"></el-input>

          <crontab @fill="fill" :expression="addsourceform.jobCron" style="width: 90%"></crontab>
        </el-form-item>

        <el-form-item v-if="addsourceform.triggerType==='2'" label="上级任务" label-width="120px">
          <el-select filterable style="width: 90%" size="mini" v-model="addsourceform.parentJobId"
                     placeholder="请选择">
            <el-option
              v-for="item in addsourceChildoptions"
              :key="item.id"
              :label="item.jobName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="addDataSource(false)">取 消</el-button>
        <el-button size="mini" type="primary" @click="addDataSource(true)">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog @close="isLogShow=false" width="90%" title="执行日志" class="logDialog"
               style="z-index:1000000;margin-top: -50px"
               :close-on-click-modal=false :visible.sync="isLogShow">
      <div :style="{ height: lastHeight-100 + 'px'}" style="overflow: auto">
        <!--        <span style="color: #fff" v-html="log"></span>-->
        <el-input type="textarea" :rows="30" readonly v-model="log"></el-input>
      </div>

    </el-dialog>
  </div>
</template>

<script>
// import defaultValue from "./components/dialogdata";
import Print from "@/util/print";
import axios from "axios";
import Crontab from "./components/crontab/index.vue";
import ElOption from "@/components/select/src/option.vue";
// import datatree from './components/dataDevelopTree.vue'
// import treehead from './components/treehead.vue'
// import containers from './components/graphContainers.vue'
// import nodeContainers from './components/nodeContainers.vue'
export default {
  name: "demo1",
  components: { ElOption, Crontab },
  data() {
    return {
      log: "",
      value: true,
      nextDate: "",
      queryform: {
        jobName: "",
        parentJobId: "",
        objType: "",
        flowRootId: ""
      },
      isLogShow: false,
      tableSize: "",
      tableData: [],
      dataSource: "",
      dialogtitle: "新增数据源",
      dialogFormVisible: false,
      addsourceoptions: [],
      collectdataoptions: [],
      addsourceChildoptions: [],
      parentJobIdoptions: [],
      flowRootIdoptions: [],
      addsourceform: {
        executorTimeout: "600",
        executorFailRetryCount:'',
        objId: "",
        objType: "1",
        parentJobId: "",
        jobName: "",
        jobCron: "",
        jobDesc: "",
        flowInfoId: "",
        triggerType: "1",
        threads: "",
        errorContinue: "1"
        // executorTimeout: "",
        // executorFailRetryCount: "",
      },
      jobId: "",
      fromrules: {
        // jobCron: { required: true, message: "请输入", trigger: "blur" },
        objId: { required: true, message: "请选择", trigger: "change" },
        jobDesc: { required: true, message: "请输入", trigger: "blur" },
        // executorTimeout: { required: true, message: "请输入", trigger: "blur" },
        // executorFailRetryCount: { required: true, message: "请输入", trigger: "blur" },
        subJobId: { required: true, message: "请选择", trigger: "blur" }
      },
      mysqlshow: false,
      hbaseinputshow: false,
      mongodbinputshow: true,
      currentPage: 1,
      pagesize: 30,
      initialaddsourceform: {},
      total: 0,
      runTest: false
    };
  },
  methods: {
    fill(data) {
      this.addsourceform.jobCron = data;
    },
    handleRadioChange() {
      this.addsourceform.objId = "";
      if (this.addsourceform.objType === "1") {
        this.getDic();
      } else {
        this.collectdata();
      }
    },
    querylog(row) {
      this.log = "";
      let querydata = {
        execId: row.execId,
        triggerDate: row.triggerDate,
        reload: true,
        server: row.server,
        flowId: row.flowId,
        triggerTime: row.triggerTime
      };
      this.$http.post("/executor/getLog", querydata).then((res) => {
        // this.log = res.data.msg.replace(/\n/g, "<br>");
        this.log = res.data.msg;
        this.isLogShow = true;
      }).finally(() => {

      });
    },
    dOJob(row) {
      if (!row.status) {
        this.$http.post("/job/closeJob", { id: row.id }).then((res) => {
          if (res.code === "200") {
            this.$message({
              // duration: 10000,
              // showClose:true,
              type: "success",
              message: "关闭成功!"
            });
          } else {
            this.$message({
              // duration: 10000,
              showClose: true,
              type: "error",
              message: "关闭失败!"
            });
          }
        }).finally(() => {
          this.queryDataSource();
        });
      } else {
        this.$http.post("/job/openJob", { id: row.id }).then((res) => {
          if (res.code === "200") {
            this.$message({
              // showClose:true,
              // duration: 10000,
              type: "success",
              message: "启动成功!"
            });
          } else {
            this.$message({
              showClose: true,
              // duration: 10000,
              type: "error",
              message: "启动失败!"
            });
          }
        }).finally(() => {
          this.queryDataSource();
        });
      }
    },
    addDataSourcedialog() {
      this.dialogtitle = "新增任务";
      this.dialogFormVisible = true;
      this.addsourceform = {
        objId: "",
        objType: "1",
        jobName: "",
        jobCron: "",
        jobDesc: "",
        flowInfoId: "",
        triggerType: "1",
        errorContinue:"1",
        parentJobId: "",
        threads: "",
        executorTimeout: "600",
        executorFailRetryCount:''
      };
      this.getDic();
      this.getChildDic();
      // Object.assign(this.addsourceform, this.initialaddsourceform);
    },
    addDataSource(data) {
      if (!data) {
        // this.$refs.addsourceformref.resetFields();
        // this.addsourceform.jobCron = '* * * * * ?'
        this.dialogFormVisible = false;
        // this.hbaseinputshow = false;
        // this.mysqlshow = false;
        // this.mongodbinputshow = true;
        return;
      }
      // await this.testDataSource("noMsg");
      this.$refs.addsourceformref.validate((valid) => {
        if (valid) {
          if (this.dialogtitle === "编辑任务") {
            let querydata = {
              id: this.addsourceform.id,
              jobCron: this.addsourceform.jobCron,
              jobDesc: this.addsourceform.jobDesc,
              jobName: this.addsourceform.jobName,
              triggerType: this.addsourceform.triggerType,
              errorContinue:this.addsourceform.errorContinue,
              objType: this.addsourceform.objType,
              objId: this.addsourceform.objId,
              threads: this.addsourceform.threads,
              executorTimeout: this.addsourceform.executorTimeout,
              executorFailRetryCount:this.addsourceform.executorFailRetryCount,
              // executorTimeout: this.addsourceform.executorTimeout,
              // executorFailRetryCount: this.addsourceform.executorFailRetryCount,
              // subJobId: this.addsourceform.subJobId.toString()
              parentJobId: this.addsourceform.parentJobId
            };
            this.$http.post("/job/modifyJob", querydata).then((res) => {
              if (res.code === "200") {
                this.$message({
                  // showClose:true,
                  type: "success",
                  message: "编辑成功!"
                });
                this.$refs.addsourceformref.resetFields();
                this.dialogFormVisible = false;
              } else {
                this.$message({
                  showClose: true,
                  type: "error",
                  message: "编辑失败!"
                });
              }
            }).finally(() => {
              this.queryDataSource();
            });
          } else {
            if (this.addsourceform.triggerType === "1") {
              this.addsourceform.parentJobId = "";
            } else {
              this.addsourceform.jobCron = "";
            }
            // if (this.addsourceform.objType === "1") {
            //   this.addsourceform.objId = "";
            // } else {
            //   this.addsourceform.flowInfoId = "";
            // }
            this.$http.post("/job/addJob", this.addsourceform).then((res) => {
              // console.log(res)
              if (res.code === "200") {
                this.$message({
                  // showClose:true,
                  type: "success",
                  message: "添加成功!"
                });
                this.$refs.addsourceformref.resetFields();
                this.dialogFormVisible = false;
              } else {
                this.$message({
                  showClose: true,
                  type: "error",
                  message: "添加失败!"
                });
              }

            }).finally(() => {
              this.queryDataSource();
            }).finally(() => {

            });
          }
        }

      });
    },
    queryDataSource() {
      this.$http.post("/job/findJobPage", {
          pageNum: this.currentPage,
          pageSize: this.pagesize,
          param: {
            jobName: this.queryform.jobName,
            parentJobId: this.queryform.parentJobId,
            objType: this.queryform.objType,
            flowRootId: this.queryform.flowRootId

          }
        }
      ).then((res) => {
        res.data.list.forEach((item) => {
          if (item.status === "1") {
            item.status = true;
          } else {
            item.status = false;
          }
        });
        this.tableData = res.data.list;
        this.total = res.data.total;
      }).finally(() => {
      });

    },
    runDataSource(row) {
      this.$http.post("/job/startJob", { id: row.id, threads: row.threads, objType: row.objType, objId: row.objId }
      ).then((res) => {
        if (res.code === "200") {
          this.$message({
            // showClose:true,
            type: "success",
            message: "启动成功!"
          });
        } else {
          this.$message({
            showClose: true,
            type: "error",
            message: "启动失败!"
          });
        }
      }).finally(() => {
        this.queryDataSource();
      });
    },
    stopDataSource(row) {
      let querydata = {
        execId: row.execId,
        row: row.triggerDate,
        server: row.server,
        flowId: row.flowId,
        triggerTime: row.triggerTime
      };
      this.$http.post("/executor/stop", querydata).then((res) => {
        // console.log(res)
        if (res.code === "200") {
          this.$message.success("停止成功");
        } else {
          this.$message({
            showClose: true,
            type: "error",
            message: `${res.msg}`
          });
        }
      });
    },
    deleteDataSource(row) {
      this.$confirm("是否删除此任务", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.$http.post("/job/deleteJob", { id: row.id }).then((res) => {
          if (res.code === "200") {
            this.$message({
              // showClose:true,
              type: "success",
              message: "删除成功!"
            });
          }
        }).finally(() => {
          this.queryDataSource();
        });
      }).catch(() => {
        this.$message({
          type: "info",
          // duration: 10000,
          message: "已取消删除"
        });
      });
    },
    editDataSource(row) {
      this.dialogtitle = "编辑任务";
      Promise.all([this.getChildDic(row.id)]).then(() => {
        this.$http.post("/job/getJob", { id: row.id }).then((res) => {
          this.jobId = res.data.id;
          this.addsourceform = res.data;
          if (res.data.objType === "1") {
            this.getDic();
          } else {
            this.collectdata();
          }
          // if(res.data.subJobId){
          //   this.addsourceform.subJobId = this.addsourceform.subJobId.split(",").map(Number);
          // }else {
          //   this.addsourceform.subJobId = []
          // }
        }).finally(() => {
          let tag = this.addsourceoptions.some((item) => item.key === row.flowInfoId);
          if (!tag) {
            this.addsourceform.flowInfoId = "";
          }
          this.dialogFormVisible = true;
        });
      });


    },
    findJobList() {
      this.$http.post("/job/findJobList").then((res) => {
        this.parentJobIdoptions = res.data;
      });
    },
    flowRootIdList() {
      this.$http.post("/sysUser/findSubject").then((res) => {
        this.flowRootIdoptions = res.data;
      });
    },
    getDic() {
      this.$http.post("/job/getFlowInfo").then((res) => {
        this.addsourceoptions = res.data;
      });
    },
    collectdata() {
      this.$http.post("/job/getDataWork").then((res) => {
        this.collectdataoptions = res.data;
      });
    },
    getChildDic(data) {
      let id = "";
      if (data) {
        id = data;
      } else {
        id = "";
      }
      return this.$http.post("/job/findSelectJobList", { id: id }).then((res) => {
        this.addsourceChildoptions = res.data;
      }).finally(() => {
        this.jobId = "";
      });
    },

    handleSizeChange(val) {
      this.pagesize = val;
      this.queryDataSource();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.queryDataSource();
    },
    queryDate(row) {
      this.$http.post("/job/getNextTime", { id: row.id }
      ).then((res) => {
        if (res.data) {
          this.nextDate = res.data.toString().replaceAll(",", "</br>");
        } else {
          this.nextDate = "";
        }


        // console.log(this.nextDate);
        // this.nextDate = '111\n111'

      });
    }
  },
  computed: {
    documentHeight() {
      return this.$store.getters.documentHeight;
    },
    lastHeight() {
      return this.documentHeight - 220;
    }
  },
  created() {
    this.findJobList();
    this.queryDataSource();
    this.getDic();
    this.collectdata();
    this.getChildDic();
    this.flowRootIdList();
    this.initialaddsourceform = Object.assign({}, this.addsourceform);

  }

};
</script>

<style scoped>


::v-deep .el-card__body {
    padding-top: 5px;
}
</style>
